#!/bin/bash

#*************************************************************************
# @file    runme
# @author  Mani Amoozadeh <maniam@ucdavis.edu>
# @author  second author name
# @date    Jan 2016
#
#/************************************************************************
# VENTOS, Vehicular Network Open Simulator; see http:?
# Copyright (C) 2013-2015
#*************************************************************************
#
# This file is part of VENTOS.
# VENTOS is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


if [ "$EUID" -eq 0 ]; then 
    printf "\e[1;31mDo not run the script with sudo permission! \e[0m \n\n"
    exit 1
fi

echo ""
echo "Bash version is: $BASH_VERSION"


##############
## Check OS ##
##############

OS='unknown'
CODENAME='unknown'
VER='unknown'
ARCH='unknown'

# get current OS information
if [[ "$OSTYPE" == "linux-gnu" || "$OSTYPE" == "linux-gnueabihf" ]]; then
    # Ubuntu
    OS=$(lsb_release -si)
    VER=$(lsb_release -sr)
    CODENAME=$(lsb_release -sc)
    ARCH=$(uname -m)
elif [[ "$OSTYPE" == "darwin"* ]]; then
    # Mac OS X
    OS=$(sw_vers -productName)
    VER=$(sw_vers -productVersion)
    ARCH=$(uname -m)
elif [[ "$OSTYPE" == "msys" ]]; then
    # windows in MINGW
    OS=$(uname -s)
    VER=$(uname -r)
    ARCH=$(uname -m)	
fi

echo "Detected OS:" $OSTYPE $OS $VER "("$CODENAME")", $ARCH

# check OS support
arrIN=(${VER//./ })  # split version into array x.y.z --> x | y | z
VER_major=${arrIN[0]}
VER_minor=${arrIN[1]}

# Ubuntu 18.04
if [[ ("$OSTYPE" == "linux-gnu" && "$OS" == "Ubuntu" && "$VER_major" == "18" && "$VER_minor" == "04") ]]; then
    echo "Starting script ..."

# Ubuntu 16.04
elif [[ ("$OSTYPE" == "linux-gnu" && "$OS" == "Ubuntu" && "$VER_major" == "16" && "$VER_minor" == "04") ]]; then
    echo "Starting script ..."

# Yosemiti (Mac OS 10.10)
elif [[ ("$OSTYPE" == "darwin"* && "$OS" == "Mac OS X" && "$VER_major" == "10" && "$VER_minor" == "10") ]]; then
    echo "Starting script ..."

# El Capitan (Mac OS 10.11)
elif [[ ("$OSTYPE" == "darwin"* && "$OS" == "Mac OS X" && "$VER_major" == "10" && "$VER_minor" == "11") ]]; then
    echo "Starting script ..."

# Sierra (Mac OS 10.12)
elif [[ ("$OSTYPE" == "darwin"* && "$OS" == "Mac OS X" && "$VER_major" == "10" && "$VER_minor" == "12") ]]; then
    echo "Starting script ..."
	
# MINGW (Git bash)
elif [[ "$OSTYPE" == "msys" ]]; then
    echo "Starting script ..."

else
    echo -n "This OS is not supported! Do you want to continue anyway? (y/n) "
    read answer
    if echo "$answer" | grep -iq "^y" ;then
        echo "Starting script ..."
    else
        exit 1 # terminate and indicate error
    fi
fi


##################
## function def ##
##################

install_LIB_linux ()
{
    declare -a argAry=("${!1}")
    for i in "${argAry[@]}"
    do
        # check if package $i is installed
        echo -n $i "..."
        PKG_OK=$(dpkg -s $i 2> /dev/null | grep "install ok installed")
        if [ "" == "$PKG_OK" ]; then
            echo "installing"
            echo $sudoPass | sudo -S apt-get --assume-yes --yes install $i > /dev/null
            # check if everything went well?
            if [[ $? -ne 0 ]]; then
                exit 1
            fi
        else
	    # this library is already installed
	    cmd_output=$(apt-cache policy $i)
	    installed_ver=$(echo "$cmd_output" | grep 'Installed: ' | awk '{print $2}')
	    candidate_ver=$(echo "$cmd_output" | grep 'Candidate: ' | awk '{print $2}')

	    # check if there exists any newer versions?
            vercomp "$candidate_ver" "$installed_ver"
            result=$?
            if [[ "$result" == "1" ]]; then
                echo "installing newer version"
                echo $sudoPass | sudo -S apt-get --assume-yes --yes install $i > /dev/null
                # check if everything went well?
                if [[ $? -ne 0 ]]; then
                    exit 1
                fi
            fi

            echo "ok"
        fi
    done
}

install_LIB_Mac ()
{
# brew list
# brew install <>
# brew remove <>
# brew search
# homebrew installs in /usr/local/Cellar/

    declare -a argAry=("${!1}")
    for i in "${argAry[@]}"
    do
        # get the last component like Caskroom/cask/xquartz
        last=$(basename $i)
        # check if package $last is installed
        echo -n $last "..."
        PKG_OK1=$(brew list | grep -w $last)
        PKG_OK2=$(brew cask list 2> /dev/null | grep -w $last)
        if [[ ("" == "$PKG_OK1") && ("" == "$PKG_OK2") ]]; then
            echo "installing"
            echo $sudoPass | sudo -S -v  # brew install might need sudo access
            brew install $i > /dev/null  # $i: we need the full package name!
            # check if everything went well?
            if [[ $? -ne 0 ]]; then
                exit 1
            fi
        else
            echo "ok"
        fi
    done
}

unpack_archive ()
{
	declare -a argAry=("${!1}")
    for i in "${argAry[@]}"
    do
		if [ -f $i ]; then
            echo -n "unpacking "$i "..."
		    ./7za x -y $i > /dev/null
		    if [[ $? -ne 0 ]]; then
                exit 1
            fi
			echo "ok"
		    rm -rf $i
        fi	
	done	
}

# wget --progress=bar:force -O gnuplot.tar.gz URL.tar.gz 2>&1 | progressfilt
progressfilt ()
{
    local flag=false c count cr=$'\r' nl=$'\n'
    while IFS='' read -d '' -rn 1 c
    do
        if $flag
        then
            printf '%c' "$c"
        else
            if [[ $c != $cr && $c != $nl ]]
            then
                count=0
            else
                ((count++))
                if ((count > 1))
                then
                    flag=true
                fi
            fi
        fi
    done
}

ascii_frag() {
    expr match "$1" "\([^[:digit:]]*\)"
}

ascii_remainder() {
    expr match "$1" "[^[:digit:]]*\(.*\)"
}

numeric_frag() {
    expr match "$1" "\([[:digit:]]*\)"
}

numeric_remainder() {
    expr match "$1" "[[:digit:]]*\(.*\)"
}

vercomp_debug() {
    OUT="$1"
    #echo "${OUT}"
}

# return 1 for $1 > $2
# return 2 for $1 < $2
# return 0 for equal
# note: this script can compare versions like 5.3p4 > 5.1
vercomp() {
    local WORK1="$1"
    local WORK2="$2"
    local NUM1="", NUM2="", ASCII1="", ASCII2=""
    while true; do
        vercomp_debug "ASCII compare"
        ASCII1=`ascii_frag "${WORK1}"`
        ASCII2=`ascii_frag "${WORK2}"`
        WORK1=`ascii_remainder "${WORK1}"`
        WORK2=`ascii_remainder "${WORK2}"`
        vercomp_debug "\"${ASCII1}\" remainder \"${WORK1}\""
        vercomp_debug "\"${ASCII2}\" remainder \"${WORK2}\""

        if [ "${ASCII1}" \> "${ASCII2}" ]; then
            vercomp_debug "ascii ${ASCII1} > ${ASCII2}"
            return 1
        elif [ "${ASCII1}" \< "${ASCII2}" ]; then
            vercomp_debug "ascii ${ASCII1} < ${ASCII2}"
            return 2
        fi
        vercomp_debug "--------"

        vercomp_debug "Numeric compare"
        NUM1=`numeric_frag "${WORK1}"`
        NUM2=`numeric_frag "${WORK2}"`
        WORK1=`numeric_remainder "${WORK1}"`
        WORK2=`numeric_remainder "${WORK2}"`
        vercomp_debug "\"${NUM1}\" remainder \"${WORK1}\""
        vercomp_debug "\"${NUM2}\" remainder \"${WORK2}\""

        if [ -z "${NUM1}" -a -z "${NUM2}" ]; then
            vercomp_debug "blank 1 and blank 2 equal"
            return 0
        elif [ -z "${NUM1}" -a -n "${NUM2}" ]; then
            vercomp_debug "blank 1 less than non-blank 2"
            return 2
        elif [ -n "${NUM1}" -a -z "${NUM2}" ]; then
            vercomp_debug "non-blank 1 greater than blank 2"
            return 1
        fi

        if [ "${NUM1}" -gt "${NUM2}" ]; then
            vercomp_debug "num ${NUM1} > ${NUM2}"
            return 1
        elif [ "${NUM1}" -lt "${NUM2}" ]; then
            vercomp_debug "num ${NUM1} < ${NUM2}"
            return 2
        fi
        vercomp_debug "--------"
    done
}


ask_for_sudo ()
{
    while true; do 
        unset sudoPass
        prompt="[sudo] password for $USER: "
        while IFS= read -p "$prompt" -r -s -n 1 char
        do
            if [[ $char == $'\0' ]]
            then
                break
            fi
            prompt='*'
            sudoPass+="$char"
        done
        echo ""

        # now check if we have sudo access?
        echo $sudoPass | sudo -k -S -v > /dev/null 2> /dev/null
        if [[ $? -eq 0 ]]; then
            break;
        else
            echo "sudo password is not correct!"
        fi
    done
}


install_java_ubuntu ()
{
    echo "[1] install OpenJDK 1.7/1.8"
    echo "[2] install Oracle Java 1.8"
    echo -n "your selection? [1] "
    read answer
    if [[ ("$answer" == "") || ("$answer" == "1") ]]; then
        # check if openjdk-8-jre has any candidates
        check=$(apt-cache policy openjdk-8-jre | grep 'Candidate:' | awk '{print $2}')
        if [[ "" != "$check" && "(none)" != "$check" ]]; then
            echo $sudoPass | sudo -S apt-get --assume-yes --yes install openjdk-8-jre
            if [[ $? -ne 0 ]]; then
                exit 1
            fi
        else
            # check if openjdk-7-jre has any candidates
            check=$(apt-cache policy openjdk-7-jre | grep 'Candidate:' | awk '{print $2}')
            if [[ "" != "$check" && "(none)" != "$check" ]]; then
                echo $sudoPass | sudo -S apt-get --assume-yes --yes install openjdk-7-jre
                if [[ $? -ne 0 ]]; then
                    exit 1
                fi
            else
                echo "openjdk-8-jre and openjdk-7-jre do not have any candidates for installation!"
                exit 1
            fi
        fi
    elif [[ "$answer" == "2" ]]; then
        echo $sudoPass | sudo -S add-apt-repository -y ppa:webupd8team/java > /dev/null
        echo $sudoPass | sudo -S apt-get update > /dev/null
        if [[ $? -ne 0 ]]; then
            exit 1
        fi
        # accept the Oracle JDK8 license automatically 
        echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | sudo /usr/bin/debconf-set-selections
        echo $sudoPass | sudo -S apt-get --assume-yes --yes install oracle-java8-installer
        # set the Java environment variables
        echo $sudoPass | sudo -S apt-get install oracle-java8-set-default > /dev/null  
        if [[ $? -ne 0 ]]; then
            exit 1
        fi     
    else
        exit 1;
    fi
}

# 0: found
# 1: older lib found
# 2: no lib found
getLibVersions_Linux ()
{
    allLIBs=$(ldconfig -p | grep $1)
    declare new_value=''
    arr=()

    # read line by line
    while IFS= read -r a; do
        loc=$(echo $a | awk '{print $4}')

        if [[ "" != "$loc" ]]; then
            # resolve if a sym link
            if [[ -h $loc ]]; then
                loc=$(readlink -f $loc)
            fi

            # first time? (removing duplicates)
            if [[ ! $new_value =~ $loc ]] ; then
                new_value="$new_value $loc"
                arr+=("$loc")
            fi
        fi
    done < <(echo "$allLIBs")

    # no lib found
    if [ ${#arr[@]} -eq 0 ]; then
        return 2
    fi

    # sort arr
    IFS=$'\n' arr=($(sort <<<"${arr[*]}"))

    # print the found libs
    echo "$1 found in these locations:"
    for i in "${arr[@]}"
    do
        echo "    $i"
    done

    for i in "${arr[@]}"
    do
        # get lib name
        libName=$(basename $i)

        # extract version
        version=$(echo $libName | grep -Po '\.so\.\K([0-9]+\.)*[0-9]+')

        # if a suitable version found!
        vercomp "$version" "$2"
        result=$?
        if ! [[ "$result" == "2" ]]; then
            return 0
        fi
    done

    # older lib found
    return 1
}

# 0: found
# 1: older lib found
# 2: no lib found
getLibVersions_Mac ()
{
    # older lib found
    return 0
}


sign_gdb ()
{
    # looking for certificate VENTOS
    exists=$(security find-identity -p codesigning -s "VENTOS" | grep "identities found" | head -n1 | xargs | awk '{print $1}')
    if [[ $exists != 0 ]]; then
        echo "certificate VENTOS already exists!"
    else
        # make a directory in omnet to store keys and certificates
        mkdir $omnetDIR/keys
        # go to the directory
        cd $omnetDIR/keys
        # check if change directory was successful (next command is dangerous!)
        if [[ $? -ne 0 ]]; then
            exit 1
        fi
        # delete whats inside keys
        rm -rf * .* 2> /dev/null

cat > myconfig.cnf << EOF

[ req ]
prompt             = no
distinguished_name = my dn

[ my dn ]
# The bare minimum is probably a commonName
commonName = VENTOS
countryName = US
localityName = VENTOS
organizationName = University of California, Davis
organizationalUnitName = EEC
stateOrProvinceName = California
emailAddress = maniam@ucdavis.edu
name = Mani
surname = Amoozadeh
givenName = Mani
initials = MA
dnQualifier = some

[ my server exts ]
keyUsage = digitalSignature
extendedKeyUsage = codeSigning

EOF
        # .key is a PEM formatted file containing just the private-key and 
        # is merely a conventional name and not a standardized one. 
        echo "generating the private key ..."
        openssl genrsa -des3 -passout pass:foobar -out server.key 2048

        # .csr is a 'Certificate Signing Request' and an application can generate it for submission to certificate-authorities. 
        # The actual format is PKCS10 which is defined in RFC 2986. It includes some/all of the key details of the requested 
        # certificate such as subject, organization, state, whatnot, as well as the public key of the certificate to get signed. 
        # -config myconfig.cnf -extensions 'my server exts' tells openssl the company name, etc. We could do this by passing the info 
        # in command line: http://stackoverflow.com/questions/8075274/is-it-possible-making-openssl-skipping-the-country-common-name-prompts 
        echo ""
        echo "generating the CSR (certificate signing request) ..."
        openssl req -new -passin pass:foobar -passout pass:foobar -key server.key -out server.csr -config myconfig.cnf -extensions 'my server exts'

        if [[ $? -ne 0 ]]; then
            exit 1
        fi

        # previously generated .csr is get signed by the CA and a certificate is returned (usually in x509 format). 
        # Note that the certificate contains the 'public key' but not the 'private key'.
        # -config myconfig.cnf -extensions 'my server exts' tells openssl to use extendedKeyUsage = codeSigning
        echo ""
        echo "generating the self-signed certificate ..."
        openssl x509 -req -passin pass:foobar -days 6666 -in server.csr -signkey server.key -out server.crt -extfile myconfig.cnf -extensions 'my server exts'

        if [[ $? -ne 0 ]]; then
            exit 1
        fi

        # .pkcs12 .pfx .p12 originally defined by RSA in the Public-Key Cryptography Standards, the "12" variant was enhanced by Microsoft. 
        # This is a passworded container format that contains both public and private certificate pairs (this container is fully encrypted)
        echo ""
        echo "convert crt + RSA private key into a PKCS12 (PFX) file ..."
        openssl pkcs12 -export -passin pass:foobar -passout pass:foobar -in server.crt -inkey server.key -out server.pfx

        # .pem Defined in RFC's 1421 through 1424, this is a container format that may include just the public certificate (such as with 
        # Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, 
        # private key, and root certificates. PEM files are not used in this script
        echo ""
        echo "convert crt + RSA private key into a PEM file ..."
        openssl x509 -inform PEM -in server.crt -out server.public.pem
        openssl rsa -passin pass:foobar -in server.key -out server.private.pem
        cat server.crt server.key > server.pem  # private key should come after

        # convert PKCS12 to PEM (this PEM contains certificate and then RSA private key)
        # openssl pkcs12 -passin pass:foobar -passout pass:foobar -in server.pfx -out server22.pem

        if [[ $? -ne 0 ]]; then
            exit 1
        fi

        echo ""
        echo "importing the certificate ..."
        echo $sudoPass | sudo -S security import server.pfx -k /Library/Keychains/System.keychain -P foobar
            
        # add-trusted-cer supports DER or PEM format (its not possible to import both cer and private key)
        sudo security add-trusted-cert -d -r trustRoot -p codeSign -k /Library/Keychains/System.keychain server.pem

        if [[ $? -ne 0 ]]; then
            exit 1
        fi

        cd ..  # go out of key folder
        cd ..  # go out of omnet folder
    fi

    # check if certificate VENTOS is trusted?
    valid=$(security find-identity -p codesigning -s "VENTOS" | grep "identities found" | tail -n1 | xargs | awk '{print $1}')
    if [[ $valid != 0 ]]; then
        echo "certificate VENTOS is trusted. Good!"
    else
        echo ""
        echo "change trust of certificate VENTOS ..."
        echo ""
        printf "\e[1;32mIn Keychain Access window, select 'System' keychains from top left and 'Certificates' category from bottom left. Right-click on certificate VENTOS and select 'Get Info'. Open the Trust item and set Code Signing to 'Always Trust'. Close Keychain Access window and re-run this script. \e[0m \n\n"
        open -a 'Keychain Access'
        exit 1
    fi

    # before signing, we should either restart or run this
    echo $sudoPass | sudo -S killall taskgated

    echo ""
    echo "signing gdb ..."
    echo $sudoPass | sudo -S codesign -s VENTOS "$(which gdb)"

    if [[ $? -ne 0 ]]; then
        exit 1
    fi
}

####################
## Starting point ##
####################

# get current directory
VENTOS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# change directory to VENTOS
cd $VENTOS_DIR

DIR_NAME=$(basename $VENTOS_DIR)
if [[ $DIR_NAME == *"VENTOS_Public"* ]]; then
    FETCH_DIR="VENTOS_Public"
elif [[ $DIR_NAME == *"VENTOS"* ]]; then
    FETCH_DIR="VENTOS"
else # the user cloned the repos under in a different name
    FETCH_DIR=$(basename `git remote show origin -n | grep "Fetch URL:" | awk '{print $NF}'`)
    if [[ "$FETCH_DIR" == "" ]]; then
        echo "cannot get the Git FETCH URL."
        exit 1
    fi
fi

# change directory to parent of VENTOS (Desktop)
cd ..
# make directory in tmp to store all downloaded files
mkdir -p /tmp/VENTOS_tmp

# ask for sudo password and save it in sudoPass
if [[ ("$OS" == "Ubuntu") || ("$OS" == "Mac OS X") ]]; then
    ask_for_sudo
fi

if [[ "$OS" == "Mac OS X" ]]; then

    # check if Command Line Tools is installed
    xcode-select -p > /dev/null 2> /dev/null
    result=$?
    if [[ $result == "2" ]]; then
        echo "installing command line tools ..."
        printf "\e[1;32mChoose the Install button in the window that pops up.\e[0m \n"
        printf "\e[1;32mAfter completion, run the script again.\e[0m \n\n"
        xcode-select --install
        exit 1
    elif [[ $result == "0" ]]; then
        ver=$(pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | grep 'version:' | awk '{print $2}')
        echo "Command line tools version $ver found!"
    fi

    # check if Homebrew is installed
    which brew
    if [[ $? != 0 ]] ; then
        # Install Homebrew
        echo ""
        echo "installing homebrew ..."
        echo $sudoPass | sudo -S -v
        # note the <
        ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null
    else
        ver=$(brew -v 2> /dev/null | awk '{print $2}')
        echo "Homebrew version $ver found!"
        echo -n "updating homebrew ... "
        brew update > /dev/null 2> /dev/null
        echo "ok"
    fi

    # installing brew cask
    echo "checking brew cask ..."
    echo $sudoPass | sudo -S -v
    brew cask list > /dev/null 2> /dev/null
fi

vercomp "$VER_major" "18"
result=$?
if [[ "$OS" == "Ubuntu" && "$result" == "2" ]]; then
    # omnet needs osgearth 2.7 or above
    echo "Adding repository ..."
    echo $sudoPass | sudo -S add-apt-repository -y ppa:ubuntugis/ppa > /dev/null
fi

if [[ "$OS" == "Ubuntu" ]]; then
    # refresh the databse of available packages
    # fixes ocational problem with java installation
    echo "updating available packages ..."
    echo $sudoPass | sudo -S apt-get update > /dev/null 2> /dev/null
fi

# get java version (if installed)
version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
if [[ "" != "$version" ]]; then
    echo "java version is" $version
fi

# should we install java?
version=$(echo $version | sed 's/_.*$//') # remove the _
vercomp "$version" "1.7"
result=$?
if [[ "$result" == "2" ]]; then
    if [[ "$OS" == "Ubuntu" ]]; then
            echo "java version should be >= 1.7"
	    install_java_ubuntu
    elif [[ "$OS" == "Mac OS X" ]]; then
        # we have already requested to install java
        echo "requesting to install java ..."
        printf "\n\e[1;32mGo to the following URL and install the latest JDK: \nhttp://www.oracle.com/technetwork/java/javase/downloads\nAfter completion, run the script again.\e[0m \n\n"
        exit 1
    fi
fi

# we need to install java 6 legacy as well
if [[ "$OS" == "Mac OS X" ]]; then
libs=("Caskroom/versions/java6")
    install_LIB_Mac libs[@]
fi

if [[ ("$OS" == "Ubuntu") || ("$OS" == "Mac OS X") ]]; then
    echo ""
    echo "Checking downloaders"
    echo "===================="
    # curl is prefered over wget since Mac OS X has curl by default
    # curl does not support parallel download
    libs=("lftp" "curl")
    if [[ "$OS" == "Ubuntu" ]]; then
        install_LIB_linux libs[@]
    elif [[ "$OS" == "Mac OS X" ]]; then
        install_LIB_Mac libs[@]
    fi
fi

# hooray
if [[ "$OS" == "Ubuntu" ]]; then
    libs=("golang-go")
    install_LIB_linux libs[@]

    echo "ipfs ...installing"
    wget -O /tmp/VENTOS_tmp/ipfs.tar.gz https://dist.ipfs.io/go-ipfs/v0.4.10/go-ipfs_v0.4.10_linux-386.tar.gz > /dev/null 2> /dev/null
    if [[ $? -ne 0 ]]; then
        exit 1
    fi
    tar xvfz /tmp/VENTOS_tmp/ipfs.tar.gz -C /tmp/VENTOS_tmp > /dev/null 2> /dev/null
    if [[ $? -ne 0 ]]; then
        exit 1
    fi
    echo $sudoPass | sudo -S mv /tmp/VENTOS_tmp/go-ipfs/ipfs /usr/local/bin/ipfs
    if [[ $? -ne 0 ]]; then
        exit 1
    fi
fi

################################
## Start OMNET++ installation ##
################################

if [[ "$OS" == "Ubuntu" ]]; then
    echo ""
    echo "Check main libraries for OMNET++"
    echo "================================"
    libs=("build-essential" "gcc" "g++" "bison" "flex" "perl" "tcl-dev" "tk-dev" "libxml2-dev" "zlib1g-dev" "doxygen" "graphviz" "libwebkitgtk-3.0-0")
    install_LIB_linux libs[@]

    echo ""
    echo "Check additional libraries for OMNET++"
    echo "======================================"
    # "openmpi-bin" and "libopenmpi-dev are for parallel simulation support (MPI)
    libs=("openmpi-bin" "libopenmpi-dev" "libpcap-dev" "gnome-color-chooser" "valgrind")
    install_LIB_linux libs[@]

    echo ""
    echo "Check 3D visualization libraries for OMNET++"
    echo "============================================"
    libs=("qt5-default" "libopenscenegraph-dev" "openscenegraph-plugin-osgearth" "osgearth" "osgearth-data" "libosgearth-dev")
    install_LIB_linux libs[@]

elif [[ "$OS" == "Mac OS X" ]]; then
    echo ""
    echo "Check main libraries for OMNET++"
    echo "================================"
    libs=("open-mpi" "Caskroom/cask/xquartz")
    install_LIB_Mac libs[@]
fi

echo ""
echo "Looking for previous OMNET++"
echo "============================"

targetVer="5.4.1"
omnetDIR="omnetpp-"$targetVer

# check if we can find omnet from the path variable
ver=$(opp_msgc 2>&1 | grep 'Version:' | awk '{print $2}' | awk -F "," '{print $1}')
loc=$(which opp_msgc 2> /dev/null)

# (in windows) if omnet is not in the path then
# we will try to look into the Version file in omnet folder
if [[ "$ver" == "" && "$OSTYPE" == "msys" ]]; then
    if [ -f "$omnetDIR/bin/opp_run" ]; then
        ver=$(cat $omnetDIR/Version | sed 's/omnetpp-//')
        loc=$(realpath $omnetDIR)
    fi
fi

if [[ "$ver" == "" ]]; then
    echo "no previous omnet++ installation found!"
else
    echo "found omnet++ $ver in"
    echo "    $loc"
fi

# (in windows) if omnet still not found, then ask the user!
if [[ "$ver" == "" && "$OSTYPE" == "msys" ]]; then
    echo -n "Do you want to install omnet++? (y/n) "
    read answer
    if ! echo "$answer" | grep -iq "^y" ; then
        WIN_OMNET_DO_NOT_INSTALL=1
    fi	
fi

# should we install a newer version?
vercomp "$ver" $targetVer
result=$?
if ! [[ "$result" == "2" ]]; then
    echo "latest omnet++ is already installed!" # jump to OMNET_FINISHED:
	
elif [[ $WIN_OMNET_DO_NOT_INSTALL != "1" ]]; then # we need to install omnet

    echo ""
    echo "Downloading OMNET++"
    echo "==================="
    # check if omnet directory exists
    if [ ! -d $omnetDIR ]; then
        # searching for omnet++ archive (# xargs: remove all whitespaces)
        findings=$(find /tmp/VENTOS_tmp -name "omnetpp*.tgz" -o -name "omnetpp*.tar" -o -name "omnetpp*.zip" | wc -l | xargs)
        if [[ "$findings" = "0" ]]; then        
            echo "downloading omnet++ version" $targetVer
 
            if [[ "$OS" == "Ubuntu" ]]; then
                omnetURL="omnetpp-"$targetVer"-src-linux.tgz"
            elif [[ "$OS" == "Mac OS X" ]]; then
                omnetURL="omnetpp-"$targetVer"-src-macosx.tgz"
	    elif [[ "$OSTYPE" == "msys" ]]; then
                omnetURL="omnetpp-"$targetVer"-src-windows.zip"
            fi

            if [[ "$OS" == "Ubuntu" || "$OS" == "Mac OS X" ]]; then
		OMNET_URL="https://ipfs.omnetpp.org/release/$targetVer/$omnetURL"
		echo "URL:"$OMNET_URL
                #ipfs get -o "/tmp/VENTOS_tmp/omnetpp.tgz" "$OMNET_URL"
		wget -O /tmp/VENTOS_tmp/omnetpp.tgz $OMNET_URL
		# curl $OMNET_URL -o /tmp/VENTOS_tmp/omnetpp.tgz
                #lftp -e "pget -n 5 $omnetURL -o /tmp/VENTOS_tmp/omnetpp.tgz; bye" -p 21 -u userftp,userftp ftp://leo.ece.ucdavis.edu/download
            elif [[ "$OSTYPE" == "msys" ]]; then
                # curl is installed in MIGW by default
                curl -u userftp:userftp "ftp://leo.ece.ucdavis.edu:21/download/$omnetURL" -o /tmp/VENTOS_tmp/omnetpp.zip
            fi
		
	    # check if omnet archive is downloaded correctly
	    if [[ $? -ne 0 ]]; then
                exit 1
            fi

        elif [[ "$findings" > "1" ]]; then
            echo "ERROR: more than one omnet++ archive file exists!"
            exit 1
        fi
    
        # now that we have the file, we can extract!
        omnetFile=$(find /tmp/VENTOS_tmp -name "omnetpp*.tgz" -o -name "omnetpp*.tar" -o -name "omnetpp*.zip")
        echo "found" $omnetFile
	echo -n "extracting omnet ..."
	if [[ "$OS" == "Ubuntu" || "$OS" == "Mac OS X" ]]; then
            tar zxf $omnetFile > /dev/null
        elif [[ "$OSTYPE" == "msys" ]]; then
            unzip $omnetFile > /dev/null            
        fi	
        echo "done!"
    else
        echo $omnetDIR" folder already exists!"
    fi

    # install omnet in windows
    if [[ "$OSTYPE" == "msys" ]]; then

        echo ""
        echo "Unpacking the MinGW toolchain"
        echo "============================="

        # go to the omnet directory
        cd $omnetDIR
        # make sure we are on the right folder
        if [[ $? -ne 0 ]]; then
            exit 1
        fi
	
        omnetFULLPATH=$(pwd)
	
        cd tools
        arch=("opp-tools-win64-msys.7z" "opp-tools-win64-msys.7z" "opp-tools-win64-extra.7z" "opp-tools-win64-visualc.7z" "opp-tools-win64-mingw64.7z")
        unpack_archive arch[@]
	
        echo -n "running QtBinPatcher... "
        win64/mingw64/bin/qtbinpatcher.exe '--qt-dir=win64\mingw64' > /dev/null
        echo "ok"
	
        # go back to OMNET folder
        cd ..
	
        echo ""
        echo "Running OMNET++ configure/make"
        echo "=============================="	
	
        echo "please wait..."
	
        # convert 'bash path' to 'cmd path' -- note the backslash at the end
        omnetFULLPATH_CMD=$(cygpath -w ${omnetFULLPATH})'\'
	
        # define new environment variables (from omnet/tools/win64/etc/bash.bashrc)
        OMNETPP_ROOT=${omnetFULLPATH}
        TCL_LIBRARY=/mingw64/lib/tcl8.6
        TERM=xterm-256color	
	
        # path to mintty
        minttyPATH=${omnetFULLPATH}/tools/win64/usr/bin/
	
        # removing previous copies of scripts
        rm -rf $minttyPATH/bash_script
        rm -rf cmd_script.cmd

# save bash script into bash_script file
cat > $minttyPATH/bash_script << EOF

#!/bin/bash

# adding omnet's bin folder to path 
export PATH=${OMNETPP_ROOT}/bin:$PATH

echo ""
echo "Running OMNET++ configure"
echo "========================="

./configure > /dev/null

echo ""
echo "Making OMNET++"
echo "=============="

printf "\e[1;32mcompiling takes some time, so relax, grab a cup of coffee and \nwatch: https://youtu.be/494dUevcqJM \e[0m \n"
echo " "
make -j4 > /dev/null
if [[ $? -ne 0 ]]; then
    echo ""
    echo "make encountered an error."
    read -n1 -r -p "Press space to continue..." key
    exit 1
fi
    echo "make is finished!"

    read -n1 -r -p "Press space to continue..." key
  
EOF

# save BATCH script to cmd_script.cmd
cat > cmd_script.cmd << EOF

@echo off
set HOME=$omnetFULLPATH_CMD

:: environment changes made after this line are local to the batch file
setlocal

:: "WD=C:\Users\ManiAm\Desktop\omnetpp-5.1\"
set "WD=%__CD__%"
if NOT EXIST "%WD%msys-2.0.dll" set "WD=%WD%\tools\win64\usr\bin\"

:: mintty is Cygwin's terminal emulator
start /wait "MinGW x64" "%WD%mintty" -d -i /msys2.ico /usr/bin/bash --login -c bash_script

EOF

        cmd //c call cmd_script.cmd
	
    fi # end of omnet install in windows

    if [[ ("$OS" == "Ubuntu") || ("$OS" == "Mac OS X") ]]; then

        echo ""
        echo "Running OMNET++ configure"
        echo "========================="

        # In the OMNET++ folder you can see the `configure.in` file that is 
        # used by autoconf to generate the `configure` script. 
        # Additional input parameters for configure script are defined in `configure.user` file.
        # The configure script detects installed software and configuration of your system, and
        # generates three outputs: `config.log`, `config.status`, and `Makefile.inc`. 
        # The first two files are used for debugging purposes, and the last file will be read later 
        # by the makefiles during the build process.

        # go to omnet directory
        cd $omnetDIR
        if [[ $? -ne 0 ]]; then
            exit 1
        fi

        omnetFULLPATH=$(pwd)

        # before running configure make sure there is no previous omnet installation in path
        ver=$(opp_msgc 2>&1 | grep 'Version:' | awk '{print $2}' | awk -F "," '{print $1}')
        vercomp "$ver" $targetVer
        result=$?
        if [[ ("" != "$ver") && ("$result" == "2") ]]; then
            help="ERROR: The PATH variable contains an old version of OMNET ($ver).
Open .bashrc file and remove the line with old OMNET path. Then 'CLOSE' this terminal
and open a new terminal and execute the runme script again!"
            printf "\n\e[1;31m$help\e[0m \n\n"
            exit 1 
        fi

        JAVA_PATH_SET=0
        OMNET_PATH_SET=0
      
        while true; do

            # run configure
            confOut=$( { ./configure > /tmp/VENTOS_tmp/out.zvapoq; } 2>&1 )
            printf "%s \n" "$confOut"

            # Qt error occurs in MAC
            if [[ "$OS" == "Mac OS X" ]]; then

                check=$(echo "$confOut" | grep "configure: error: Qtenv")
                if [ "" != "$check" ]; then
                    help="Updating variables in ~/.bash_profile for QT:"
                    printf "\n\e[1;32m$help\e[0m \n"
                    echo ""

                    # append to bash_profile
                    echo "export QT_PLUGIN_PATH=$omnetFULLPATH/tools/macosx/plugins" >> ~/.bash_profile
                    echo "export PATH=\$PATH:$omnetFULLPATH/tools/macosx/bin" >> ~/.bash_profile

                    export QT_PLUGIN_PATH=$omnetFULLPATH/tools/macosx/plugins
                    export PATH=$PATH:$omnetFULLPATH/tools/macosx/bin

                    continue # run configure again
                fi
    
            fi

            # terminate script on error
            check=$(echo "$confOut" | grep "configure: error")
            if [ "" != "$check" ]; then
                echo ""    # insert new line for readability
                exit 1
            fi

            # setting java_path
            check=$(echo "$confOut" | grep "configure: WARNING: JAVA_HOME")
            if [ "" != "$check" ]; then

                if [ "$JAVA_PATH_SET" -eq "1" ]; then
                    echo "cannot add JAVA_HOME in PATH"
                    exit 1
                fi

                if [[ "$OS" == "Ubuntu" ]]; then
                    help="Adding JAVA_HOME to bashrc ..."
                    printf "\n\e[1;32m$help\e[0m \n\n"
         
                    # append java path to .bashrc
                    JAVAHOME=$(dirname $(dirname $(dirname $(readlink -f $(which java)))))
                    echo "export JAVA_HOME=$JAVAHOME" >> ~/.bashrc 

                    # source ~/.bashrc does not work here
                    # because a shell that runs a script is not interactive.
                    export JAVA_HOME=$JAVAHOME

                elif [[ "$OS" == "Mac OS X" ]]; then
                    help="Adding JAVA_HOME to bash_profile ..." 
                    printf "\n\e[1;32m$help\e[0m \n\n"
        
                    echo "export JAVA_HOME=/usr/libexec/java_home" >> ~/.bash_profile 
                    export JAVA_HOME=/usr/libexec/java_home
                fi

                JAVA_PATH_SET=1
                continue # run configure again
            fi

            # setting omnet path
            check=$(echo "$confOut" | grep "WARNING: your PATH doesn't contain")
            if [ "" != "$check" ]; then

                if [ "$OMNET_PATH_SET" -eq "1" ]; then
                    echo "cannot add OMNET++ bin folder to PATH"
                    exit 1
                fi

                if [[ "$OS" == "Ubuntu" ]]; then
                    help="Adding OMNET++ bin folder to PATH ..."
                    printf "\n\e[1;32m$help\e[0m \n\n"
         
                    echo "export PATH=\$PATH:$omnetFULLPATH/bin" >> ~/.bashrc 

                    # source ~/.bashrc does not work here
                    # because a shell that runs a script is not interactive.
                    export PATH=$PATH:$omnetFULLPATH/bin

                elif [[ "$OS" == "Mac OS X" ]]; then
                    help="Adding OMNET++ bin folder to PATH ..." 
                    printf "\n\e[1;32m$help\e[0m \n\n"

                    echo "export PATH=\$PATH:$omnetFULLPATH/bin" >> ~/.bash_profile 
        
                    export PATH=$PATH:$omnetFULLPATH/bin
                fi

                OMNET_PATH_SET=1
                continue # run configure again
            fi

            break # break out of the while loop

        done # end of while loop

    fi # end of omnet configure in ubuntu/mac os x

    if [[ ("$OS" == "Ubuntu") || ("$OS" == "Mac OS X") ]]; then

        echo ""
        echo "Making OMNET++"
        echo "=============="

        # start making omnet++
        printf "\e[1;32mcompiling takes some time, so relax, grab a cup of coffee and \nwatch: https://www.youtube.com/watch?v=A6XUVjK9W4o \e[0m \n"
        echo " "
        make -j4 > /dev/null
        if [[ $? -ne 0 ]]; then
            exit 1
        fi
        echo "make is finished!"

    fi # end of omnet make

    echo ""
    echo "Creating shortcut"
    echo "================="

    # Running OMNET++ each time from command line might not be desirable for you. 
    # You can create a shortcut or launcher to OMNET++ on your desktop.

    if [[ ("$OS" == "Ubuntu") || ("$OS" == "Mac OS X") ]]; then

        echo -n "creating desktop shortcut ... "
        make install-desktop-icon > /dev/null 2> /dev/null
        echo "done!"

        echo -n "creating application launcher ... "
        echo $sudoPass | sudo -S make install-menu-item > /dev/null 2> /dev/null
        echo "done!"
	
    elif [[ "$OSTYPE" == "msys" ]]; then
	
        echo "To open OMNET++ run mingwenv.cmd and type omnetpp"
	
    fi

    # go out of omnetpp folder
    cd ..

# OMNET_FINISHED:
fi

if [[ ("$OS" == "Ubuntu") || ("$OS" == "Mac OS X") ]]; then

    echo ""
    echo "Check gdb"
    echo "========="

    which gdb 2> /dev/null
    if [[ $? != 0 ]] ; then
        # install gdb for debugging in eclipse
        if [[ "$OS" == "Ubuntu" ]]; then
            libs=("gdb")
            install_LIB_linux libs[@]
        elif [[ "$OS" == "Mac OS X" ]]; then
            libs=("gdb" "openssl")
            install_LIB_Mac libs[@]
        fi
    else
        echo "gdb found in"
        echo "    $(which gdb)"
    fi

    # OS X 10.9 and later requires that you sign the gdb executable with a certificate
    if [[ "$OS" == "Mac OS X" ]]; then
        autho=$(codesign --display --verbose=4 $(which gdb) 2>&1 | grep 'Authority')
        if [[ "" != "$autho" ]]; then
            echo "gdb is signed with $autho"
        else
            echo "gdb is not signed!"
            sign_gdb
            # show a message that user needs to change the path to gdb
            printf "\e[1;32mDo not forget to modify 'GDB debugger' in OMNET++ Eclipse to \e[0m \n"
            printf "\e[1;32m    "$(which gdb)" \e[0m \n"
        fi
    fi

fi # end of gdb check


################################
## Start of SUMO installation ##
################################
# following instructions in here
# http://sumo.dlr.de/wiki/Installing/MacOS_Build_w_Homebrew

# change directory to VENTOS
cd $VENTOS_DIR
if [[ $? -ne 0 ]]; then
    exit 1
fi
# change directory to parent of VENTOS
cd ..

echo ""
echo "Check main libraries for SUMO"
echo "============================="

if [[ "$OS" == "Ubuntu" ]]; then
    # should we add "libxerces-c2-dev" ? installing libgdal-dev removes libxerces-c2-dev!
    libs=("libtool" "automake" "autoconf" "pkg-config" "libfox-1.6-dev" "libproj-dev" "libgdal-dev" "python")
    install_LIB_linux libs[@]
elif [[ "$OS" == "Mac OS X" ]]; then
    libs=("libtool" "automake" "autoconf" "pkg-config" "homebrew/x11/fox" "proj" "gdal" "xerces-c")
    install_LIB_Mac libs[@]
fi

echo ""
echo "Looking for previous SUMO"
echo "========================="

ver=$(sumo 2> /dev/null | grep 'SUMO Version' | awk '{print $3}')
if [[ "" != "$ver" ]]; then
    loc=$(which sumo)
    echo "found SUMO $ver in"
    echo "    $loc"

    # look for 'VENTOS_SUMO' file in the bin folder
    VENTOS_SUMO_FILE=$(dirname "${loc}")"/VENTOS_SUMO"
    if [[ ! -f $VENTOS_SUMO_FILE ]]; then
        help="ERROR: The installed SUMO version interferes with VENTOS_SUMO.
Open .bashrc file and remove the current SUMO path. Then CLOSE this terminal
and open a new terminal and execute the runme script again!"
        printf "\n\e[1;31m$help\e[0m \n\n"
        exit 1 
    fi

    echo "skip downloading/making SUMO"    
else
    echo "no previous SUMO installation found!"

    echo ""
    echo "Cloning SUMO git repository"
    echo "==========================="

    if [[ "$FETCH_DIR" == "VENTOS" ]]; then
        SUMO_DIR="VENTOS_SUMO"
        VENTOS_SUMO_GIT="https://github.com/ManiAm/VENTOS_SUMO"
    elif [[ "$FETCH_DIR" == "VENTOS_Public" ]]; then
        SUMO_DIR="VENTOS_SUMO_Public"
        VENTOS_SUMO_GIT="https://github.com/ManiAm/VENTOS_SUMO_Public"
    else
        echo "$FETCH_DIR is not valid!"
        exit 1
    fi

    # check if SUMO directory exists
    if [ ! -d "$SUMO_DIR" ]; then
        # cloning git
        if ! git clone $VENTOS_SUMO_GIT; then
            exit 1
        fi
        # make sure the folder is created
        if [[ ! -d "$SUMO_DIR" ]]; then
            echo "$SUMO_DIR folder does not exist!"
            exit 1
        fi
    else
        echo "$SUMO_DIR folder already exists!"
    fi

    echo ""
    echo "Running SUMO configure"
    echo "======================"

    cd $SUMO_DIR
    if [[ $? -ne 0 ]]; then
        exit 1
    fi

    if [[ "$OS" == "Mac OS X" ]]; then
        # homebrew installs xquartz in /opt/x11/
        export CPPFLAGS="$CPPFLAGS -I/opt/X11/include/"
        export LDFLAGS="-L/opt/X11/lib"
    fi

    echo "generating configure file ..."
    make -f Makefile.cvs > /dev/null

    SUMO_PATH_SET=0

    while true; do

        echo "running configure ..."
        confOut=$( { ./configure --enable-debug --with-proj-gdal=/usr > /tmp/VENTOS_tmp/out.xzevap; } 2>&1 )
        printf "%s \n" "$confOut"

        # should we terminate this script
        check=$(echo "$confOut" | grep -e "error" -e "configure: WARNING")
        if [ "" != "$check" ]; then
            echo ""    # insert new line for readability
            exit 1
        fi

        # check if SUMO bin is in the path
        SUMO_BIN_DIR=$(pwd)"/bin"
        if [[ ! -d $SUMO_BIN_DIR ]]; then
            echo "The $SUMO_BIN_DIR directory does not exist!"
            exit 1
        else
            # ...then we create a small tmp file to check if the dir is in the path
            probefile=__second__probe__

            echo '' >$SUMO_BIN_DIR/$probefile
            chmod +x  $SUMO_BIN_DIR/$probefile

            if ($probefile) >/dev/null 2>/dev/null; then
                echo "Your PATH contains $SUMO_BIN_DIR. Good!"
            else

                if [ "$SUMO_PATH_SET" -eq "1" ]; then
                    echo "cannot add SUMO bin folder to PATH"
                    exit 1
                fi

                # setting sumo path
                if [[ "$OS" == "Ubuntu" ]]; then
                    help="Adding SUMO bin folder to PATH ..."
                    printf "\e[1;32m$help\e[0m \n\n"
         
                    echo "export PATH=\$PATH:$SUMO_BIN_DIR" >> ~/.bashrc 

                    # source ~/.bashrc does not work here
                    # because a shell that runs a script is not interactive.
                    export PATH=$PATH:$SUMO_BIN_DIR

                elif [[ "$OS" == "Mac OS X" ]]; then
                    help="Adding SUMO bin folder to PATH ..." 
                    printf "\e[1;32m$help\e[0m \n\n"

                    echo "export PATH=\$PATH:$SUMO_BIN_DIR" >> ~/.bash_profile 

                    export PATH=$PATH:$SUMO_BIN_DIR
                fi

                # removing the prob file
                rm $SUMO_BIN_DIR/$probefile
                SUMO_PATH_SET=1
                continue
            fi

            # removing the prob file
            rm $SUMO_BIN_DIR/$probefile
        fi
  
        break

    done # end of while loop (sumo configure)

    echo ""
    echo "Making SUMO"
    echo "==========="

    # start making SUMO
    printf "\e[1;32mcompiling takes some time, so relax and \nwatch: https://youtu.be/vLT3A0a3hoQ \e[0m \n"
    echo " "
    make -j4 > /dev/null
    if [[ $? -ne 0 ]]; then
        exit 1
    fi
    echo "make is finished!"

    # go out of VENTOS_SUMO folder
    cd ..

fi # end of SUMO installation


###############################
## Start VENTOS installation ##
###############################

# change directory to VENTOS
cd $VENTOS_DIR
if [[ $? -ne 0 ]]; then
    exit 1
fi
# change directory to parent of VENTOS
cd ..

echo ""
echo "Check main libraries for VENTOS"
echo "==============================="

if [[ "$OS" == "Ubuntu" ]]; then

    # we need boost 1.48 at minimum    
    libs=("libboost-all-dev" "libssl-dev" "libcurl4-gnutls-dev" "libbluetooth-dev" "libgtkmm-3.0-dev")
    install_LIB_linux libs[@]

elif [[ "$OS" == "Mac OS X" ]]; then

    echo $sudoPass | sudo -S chown -R $(whoami) /usr/local/share/pkgconfig
    brew link shared-mime-info
    libs=("boost" "gtkmm3")
    install_LIB_Mac libs[@]
fi

# cd to tmp
cd /tmp/VENTOS_tmp
if [[ $? -ne 0 ]]; then
    exit 1
fi

echo ""
echo "Check cmake"
echo "==========="

# install cmake lib
if [[ "$OS" == "Ubuntu" ]]; then
    libs=("cmake" "cmake-curses-gui")
    install_LIB_linux libs[@]
elif [[ "$OS" == "Mac OS X" ]]; then
    libs=("cmake")
    install_LIB_Mac libs[@]
fi

# check the cmake version (shark needs higher versions!)
version=$(cmake -version | grep ^'cmake version' | sed 's/^.* //g')
echo "cmake version is" $version

# should we install a newer version?
vercomp "$version" "3.1"
result=$?
if ! [[ "$result" == "1" ]]; then
    if [ ! -d "CMake" ]; then
        echo "downloading CMake"
        curl -o cmake.zip -LOk https://github.com/Kitware/CMake/archive/master.zip
        if [[ $? -ne 0 ]]; then
            exit 1
        fi
        unzip cmake.zip -d CMake > /dev/null
    fi

    cd CMake
    cd CMake-master
    if [[ $? -ne 0 ]]; then
        exit 1
    fi

    echo "installing cmake ..."
    mkdir _build
    cd _build
    cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr > /dev/null
    if [[ $? -ne 0 ]]; then
        exit 1
    fi
    make
    if [[ $? -ne 0 ]]; then
        exit 1
    fi
    echo $sudoPass | sudo -S make install > /dev/null
    if [[ "$OS" == "Ubuntu" ]]; then
        echo $sudoPass | sudo -S ldconfig  # we need cmake in the next step
    fi

    cd ..
    cd ..
    cd ..
fi

echo ""
echo "Check gnuplot"
echo "============="

# install gnuplot
if [[ "$OS" == "Ubuntu" ]]; then
    libs=("gnuplot" "gnuplot-x11")
    install_LIB_linux libs[@]
elif [[ "$OS" == "Mac OS X" ]]; then
    libs=("gnuplot")
    install_LIB_Mac libs[@]
fi

# check version
version=$(gnuplot --version | awk '{print $2}')
echo "gnuplot version is" $version

# should we install a newer version?
vercomp "$version" "5.0"
result=$?
if [[ "$result" == "2" ]]; then
    if [ ! -d "gnuplot" ]; then
        echo "downloading gnuplot"
        lftp -e 'pget -n 2 gnuplot-5.0.3.tar.gz -o /tmp/VENTOS_tmp/gnuplot.tar.gz; bye' -p 21 -u userftp,userftp ftp://leo.ece.ucdavis.edu/download
        if [[ $? -ne 0 ]]; then
            exit 1
        fi
        mkdir gnuplot
        tar zxf gnuplot.tar.gz -C gnuplot --strip 1
    fi

#libgd-dev
#liblua5.2-dev
#libwxgtk2.8-dev

    cd gnuplot
    if [[ $? -ne 0 ]]; then
        exit 1
    fi

    echo "installing gnuplot ..."
    ./configure > /dev/null 2> /dev/null
    make > /dev/null
    if [[ $? -ne 0 ]]; then
        exit 1
    fi
    echo $sudoPass | sudo -S make install > /dev/null

    cd ..
fi


echo ""
echo "check eigen"
echo "==========="

# Eigen consists only of header files, hence there is nothing to compile before you can use it. The header files will be copied into /usr/local/include.

if [ -d "/usr/local/include/eigen3/Eigen" ]; then
    echo "eigen is already installed!"
else
    if [ ! -d "eigen" ]; then
        echo "downloading eigen"
        curl -o eigen.zip -LOk https://github.com/eigenteam/eigen-git-mirror/archive/master.zip
        if [[ $? -ne 0 ]]; then
            exit 1
        fi
        unzip eigen.zip -d eigen > /dev/null
    fi

    cd eigen
    cd eigen-git-mirror-master
    if [[ $? -ne 0 ]]; then
        exit 1
    fi

    echo "installing eigen ..."
    mkdir build
    cd build
    cmake ../ > /dev/null
    if [[ $? -ne 0 ]]; then
        exit 1
    fi
    echo $sudoPass | sudo -S make install > /dev/null

    cd ..
    cd ..
    cd ..
fi


echo ""
echo "check shark"
echo "==========="

# libshark library will be copied into /usr/local/lib and the header files will be copied into /usr/local/include.
# in mac os x, brew install shark does not make symbolic links for include:
# sudo ln -s /usr/local/Cellar/shark/3.0.0/include/shark /usr/local/include
# moreover, we need shark_debug shared library. So shark should be compiled manually!

if [[ "$OS" == "Ubuntu" ]]; then
    libs=("libatlas-base-dev")
    install_LIB_linux libs[@]

    getLibVersions_Linux "libshark" "3.0.0"
elif [[ "$OS" == "Mac OS X" ]]; then
    getLibVersions_Mac "libshark" "3.0.0"
fi

result=$?
#if [[ ("$result" == "1") || ("$result" == "2") ]]; then
if [[ 1 ]]; then
    if [ ! -d "Shark" ]; then
        echo "downloading shark"
        curl -o shark.zip -LOk https://github.com/Shark-ML/Shark/archive/master.zip
        if [[ $? -ne 0 ]]; then
            exit 1
        fi
        unzip shark.zip -d Shark > /dev/null
    fi

    cd Shark
    cd Shark-master
    if [[ $? -ne 0 ]]; then
        exit 1
    fi

    echo "installing shark ..."
    mkdir build
    cd build
    cmake "-DBUILD_EXAMPLES=OFF" "-DBUILD_TESTING=OFF" "-DBUILD_SHARED_LIBS=ON" "-DCMAKE_BUILD_TYPE=Debug" ../ > /dev/null
    make 
    if [[ $? -ne 0 ]]; then
        exit 1
    fi
    echo $sudoPass | sudo -S make install > /dev/null
    if [[ $? -ne 0 ]]; then
        exit 1
    fi

    cd ..
    cd ..
    cd ..
else
    echo "libshark is already installed!"
fi


######################
## Finishing up ... ##
######################

# change directory to VENTOS
cd $VENTOS_DIR
if [[ $? -ne 0 ]]; then
    exit 1
fi
# change directory to parent of VENTOS
cd ..

echo ""
echo "Wrapping-up"
echo "==========="

if [[ "$OS" == "Ubuntu" ]]; then
    # ldconfig is a program that is used to maintain the shared library cache in linux. This cache is typically stored in the file /etc/ld.so.cache and is used by the system to map a shared library name to the location of the corresponding shared library file.
    echo -n "registering shared libraries ..."
    echo $sudoPass | sudo -S ldconfig
    echo "done!"

    # fix tooltip
    echo -n "do you wish to fix tooltip colors? (y/n) "
    read answer
    if echo "$answer" | grep -iq "^y" ;then
        printf "\e[1;32mOn the Specific tab, find the Tooltips group and change the settings to 'black' foreground over 'pale yellow' background. Click Apply and then Close.\e[0m \n\n"
        gnome-color-chooser 2> /dev/null
    fi
fi

echo -n "removing temporary data ..."
echo $sudoPass | sudo -S rm -rf /tmp/VENTOS_tmp
echo "done!"

echo ""
echo "finished!"

